use crate::{println, print};
use crate::string::String;
use x86_64::instructions::hlt;
use crate::driver::keyboard::{KEYBOARD_BUFFER, INDEX};

pub struct Kernel;

impl Kernel {
    pub fn new() -> Self {
        Self
    }

    pub fn run(&self) {
        println!("Welcome to Kito!");
        crate::init::init();
        
        // Shell实现
        println!("Type 'help' for available commands");
        
        loop {
            print!("$ ");
            
            // 等待用户输入
            let mut command = String::new();
            let mut index = crate::driver::keyboard::INDEX.lock();
            let buffer = crate::driver::keyboard::KEYBOARD_BUFFER.lock();
            
            // 读取输入直到回车
            while *index < buffer.len() && buffer[*index] != b'\n' {
                command.push_str();
                *index += 1;
            }
            
            // 处理回车
            if *index < buffer.len() && buffer[*index] == b'\n' {
                *index += 1; // 跳过换行符
                
                // 解析并执行命令
                match command.trim() {
                    "help" => {
                        println!("Available commands:");
                        println!("  help - Show this help");
                        println!("  clear - Clear the screen");
                        println!("  echo [text] - Print text");
                    }
                    "clear" => {
                        crate::vga::WRITER.lock().clear_screen();
                    }
                    "" => {} // 空命令不做任何事
                    cmd if cmd.starts_with("echo ") => {
                        println!("{}", &cmd[5..]);
                    }
                    _ => {
                        println!("Unknown command: {}", command);
                    }
                }
            }
        }
    }
}
